package com.lh.glorypavilion.service.ucenter.controller;

import com.lh.glorypavilion.exception.glorypavilionEx;
import com.lh.glorypavilion.result.R;
import com.lh.glorypavilion.result.ResultCode;
import com.lh.glorypavilion.service.ucenter.entity.vo.LoginVo;
import com.lh.glorypavilion.service.ucenter.service.IMemberService;
import com.lh.glorypavilion.util.JwtInfo;
import com.lh.glorypavilion.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

//@CrossOrigin//允许跨域
@RestController
@RequestMapping("/user")
@Slf4j
public class loginController {

    @Autowired
    private IMemberService memberService;

    @ApiOperation("登录")
    @PostMapping("login/{username}/{password}")
    public R login(@ApiParam(value = "手机号",required = true) @PathVariable String username,
                   @ApiParam(value = "密码",required = true) @PathVariable String password){
        LoginVo loginVo = new LoginVo();
        loginVo.setMobile(username);
        loginVo.setPassword(password);
        String token=memberService.login(loginVo);
        return R.ok().data("token",token).message("登录成功");
    }

    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public R info(HttpServletRequest request){
        try {
            JwtInfo jwtInfo = JwtUtils.getMemberIdByJwtToken(request);
            return R.ok().data("name", jwtInfo.getNickname()).data("roles","管理员").data("avatar",jwtInfo.getAvatar());
        } catch (Exception e) {;
            log.error("解析用户信息失败：" + e.getMessage());
            throw new glorypavilionEx(ResultCode.FETCH_USERINFO_ERROR);
        }
    }

}
